import java.util.HashMap;
import java.util.LinkedList;

public class MinDepth {

    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        HashMap<TreeNode, Integer> map = new HashMap<>();
        int curLevel = 1;
        map.put(root, 1);
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (map.get(node) != curLevel) {
                curLevel++;
            }
            if (node.right == null && node.left == null) return curLevel;
            if (node.left != null) {
                queue.add(node.left);
                map.put(node.left, curLevel + 1);
            }
            if (node.right != null) {
                queue.add(node.right);
                map.put(node.right, curLevel + 1);
            }
        }
        return -1;
    }
}
